package com.huwaiwai001.echo.nio.client;

import com.huwaiwai001.echo.constant.ServerInfo;
import com.huwaiwai001.echo.util.InputUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by hww on 2019/3/18 14:07.
 */
public class EchoNioClientHandler implements AutoCloseable {

    private SocketChannel socketChannel;

    EchoNioClientHandler() throws IOException {
        this.socketChannel = SocketChannel.open();
        this.socketChannel.connect(new InetSocketAddress(ServerInfo.ECHO_HOST, ServerInfo.ECHO_PORT));
        System.out.println("客户端 启动成功 " + ServerInfo.ECHO_HOST + ":" + ServerInfo.ECHO_PORT);
    }

    void handle() throws Exception {
        // 开辟一个缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(50);
        boolean flag = true;
        while (flag) {
            // 清除缓冲区
            buffer.clear();
            // 读取控制台输入
            String msg = InputUtil.getString("请输入要发送的内容");
            // 写入缓冲区
            buffer.put(msg.getBytes());
            // 切换模式
            buffer.flip();
            // 写入通道
            this.socketChannel.write(buffer);
            // 清空缓冲区
            buffer.clear();
            // 读取通道响应
            int readCount = this.socketChannel.read(buffer);
            // 切换缓冲区
            buffer.flip();
            // 读取响应
            System.out.println(new String(buffer.array(),0,readCount)); // 输出信息
            if ("exit".equalsIgnoreCase(msg)) {
                flag = false ;
            }
        }
    }

    @Override
    public void close() throws Exception {
        this.socketChannel.close();
    }
}
